package org.wltea.analyzer.db;

import org.apache.logging.log4j.Logger;
import org.wltea.analyzer.dic.Dictionary;
import org.wltea.analyzer.help.ESPluginLoggerFactory;

import java.security.AccessController;
import java.security.PrivilegedAction;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ZH
 * @since: 2024/10/21
 */
public class JdbcUtils {
    private static final Logger logger = ESPluginLoggerFactory.getLogger(Dictionary.class.getName());
    static {
        try {
            AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
                try {
                    // 加载 MySQL JDBC 驱动
                    Class.forName("com.mysql.cj.jdbc.Driver");
                    logger.info("MySQL JDBC Driver loaded successfully.");
                } catch (ClassNotFoundException e) {
                    logger.error("MySQL JDBC Driver not found.");
                    e.printStackTrace();
                }
                return null;
            });
        } catch (Exception e) {
            System.err.println("An error occurred while loading the MySQL JDBC Driver.");
            e.printStackTrace();
        }
    }

    public static Connection getConnection(String url, String user, String password) throws SQLException {
        Connection connection;
        connection = AccessController.doPrivileged((PrivilegedAction<Connection>) () -> {
            try {
                return DriverManager.getConnection(
                        url,
                        user,
                        password
                );
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        });
        return connection;
    }
    public static List<String[]> executeQuery(Connection connection, String sql) {
        List<String[]> results = new ArrayList<>();

        AccessController.doPrivileged((PrivilegedAction< List<String[]>>) () -> {
            try (PreparedStatement preparedStatement = connection.prepareStatement(sql);
                 ResultSet resultSet = preparedStatement.executeQuery()) {

                ResultSetMetaData metaData = resultSet.getMetaData();
                int columnCount = metaData.getColumnCount();

                while (resultSet.next()) {
                    String[] row = new String[columnCount];
                    for (int i = 0; i < columnCount; i++) {
                        row[i] = resultSet.getString(i + 1);
                    }
                    results.add(row);
                }
            } catch (SQLException e) {
                logger.error("查询执行失败: " + e.getMessage());
            }
            return results;
        });
        return results;
    }
}
